<?php

namespace Site\FacebookDisplayBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

use \BaseFacebook;
use \FacebookApiException;
class DefaultController extends Controller
{
  public function indexAction($groupId)//automatisé le controleur
  { 
    $facebook = $this->get('fos_facebook.api');
    $helper = $facebook->getLoginUrl();
    $uid = $facebook->getUser();
    $group = $this->getFeedAppGroup($groupId,$facebook);
      
    $filesGroup = $this->getFilesGroupe($groupId,$facebook);
      
    $send = array();
    $links = array();
    $hotline = array();
    $i = 0;
    $cpt = 0;
    foreach($group['data'] as $message)
      {
	if($message['from']['id']==$facebook->getAppId())
	  {
	    $hotline[$cpt]['message']=$message['message'];
	    $hotline[$cpt]['date']=$message['updated_time'];
	    $cpt++;
	  }
	$send[$i]['message']=$message['message'];
	$send[$i]['name']=$message['from']['name'];
	$send[$i]['date']=$message['updated_time'];
	$send[$i]['url']=$this->getUrlUserPicture($message['from']["id"],$facebook,100,100)["data"]["url"];
	if(array_key_exists('link',$message))
	  {
	    array_push($links,$message['link']);
	  }
	$y=0;
	if(array_key_exists('comments',$message)){
	  foreach($message['comments']['data'] as $comment)
	    {
	      $send[$i]['comments'][$y]['message']=$comment['message'];
	      $send[$i]['comments'][$y]['name']=$comment['from']['name'];
	      $send[$i]['comments'][$y]['date']=$comment['created_time'];
	      $send[$i]['comments'][$y]['url']=$this->getUrlUserPicture($comment['from']['id'],$facebook,100,100)['data']['url'];
	      $y++;
	    }
	}
	else{ $send[$i]['comments']="";}
	    
	$i++;
      }
      
      
  
    return $this->render('SiteFacebookDisplayBundle:Default:facebookTest.html.twig', array('grpfb'=>$send,'files'=>$filesGroup,'links'=>$links,'group'=>$group,'uid'=>$uid,'url'=>$helper,'groupId'=>$groupId,'hotline'=>$hotline));
    /*      return $this->render('SiteFacebookDisplayBundle:Default:index.html.twig',array('group'=>$group ));*/
      
  }
  
  
    
  //Photo
  public function getUrlUserPicture($user_id,BaseFacebook $facebook,$height,$wigth)
  {
    if($user_id)
      {
	try{
	  $user_picture = $facebook->api($user_id.'/picture','GET',array(
									 'redirect'=>false,
									 'height'=>$height,
									 'type'=>'small',
									 'width'=>$wigth
									 ));
	  return $user_picture;
	}catch(FacebookApiException $e){
	  $this->ExCatch($e,$facebook);
	}
      }
    return 0;
  }
    
  public function getUserFriends($user_id,BaseFacebook $facebook){
    if($user_id)
      {
	try{
	  $user_friends = $facebook->api('/me/friends?fields=picture','GET');
	  return $user_friends;
	}catch(FacebookApiException $e){
	  $this->ExCatch($e,$facebook);
	}
      }
    return 0;
  }
  //Groups de l'application
  public function getGroupsApp(BaseFacebook $facebook){
    try{
      $app_groups = $facebook->api("app/groups",'GET');
      return $app_groups;
    }catch (FacebookApiException $e){
      $this->ExCatch($e,$facebook);
    }
    return 0;
  }
    
  //Feeds d'un group donné
  public function getFeedAppGroup($id_group,BaseFacebook $facebook){
    try{
      $feed_group=$facebook->api($id_group."/feed?fields=link,message,from,comments","GET");
      return $feed_group;
    }catch (FacebookApiException $e){
      $this->ExCatch($e,$facebook);
    }
  }

  public function getComment($id_comment,BaseFacebook $facebook){
    try{
      $comment = $facebook->api($id_comment,"GET");
      return $comment;
    }catch(FacebookApiException $e){
      $this->ExCatch($e,$facebook);
    }
  }

  //Message
  public function getMessage($id_message,BaseFacebook $facebook){
    try{
      $message=$facebook->api($id_message,"GET");
      return $message;
    }catch(FacebookApiException $e){
      $this->ExCatch($e,$facebook);
    }
  }
  //File Group
  public function getFilesGroupe($id_groupe,BaseFacebook $facebook)
  {
    try{
      $files=$facebook->api($id_groupe.'/files?fields=download_link,message','GET');
      return $files;
    }catch(FacebookApiException $e){
      $this->ExCatch($e,$facebook);
    }
  }
    
  public function creerGroup($nomgroup,BaseFacebook $facebook)
  {
    $response=$facebook->api($facebook->getAppId()."/groups","POST",array('name'=> $nomgroup,'access_token'=>$facebook->getApplicationAccessToken()));
    return $response;
  }


  public function deleteGroup($groupId,BaseFacebook $facebook)
  {
    $response=$facebook->api($facebook->getAppId()."/groups/".$groupId,"DELETE",array('access_token'=>$facebook->getApplicationAccessToken()));
    return $response;
			     
  }

  public function deleteMemberGroup($uid,$groupId,BaseFacebook $facebook)
  {
    $response = $facebook->api($groupId."/members","DELETE",array('member'=> $uid, 'access_token'=>$facebook->getApplicationAccessToken()));
    return $response;
  }


  //Liste membres
  public function membersGroups(BaseFacebook $facebook)
  {
    try{
      $group_members = $facebook->api($facebook->getAppId().'/groups','GET',array("fields"=>"members,name"));
      foreach ( $group_members['data'] as $group)
	{
	  if(!isset($group['members']))
	    {
	      $group['members'][0]['name']="Pas de membres...";
	      $group['membres'][0]['id']=0;
	    }
	}
      return $group_members;
		    
    }catch(FacebookApiException $e){
      $this->ExCatch($e,$facebook);
    }
      
    return 0;
	
  }
    
    public function inviterGroup($idGrp,$idu,BaseFacebook $facebook)
    { try{
    $invite=$facebook->api("/".$idGrp."/members","POST",array( 'member'=> $idu,'access_token'=>$facebook->getApplicationAccessToken() ));
    return $invite;
    }catch(FacebookApiException $e){
      $this->ExCatch($e,$facebook);
    }
    return 0;
  }

  public function creerGroupAction(Request $request)
  {
    $facebook = $this->get('fos_facebook.api');
    $idgroup= $request->query->get('idgroup');
    $resp = $this->creerGroup($idgroup,$facebook);
    return $this->redirect($this->generateUrl('site_facebook_display_admin'));
  }
  
   public function deleteAction($groupId)
  {
    $facebook = $this->get('fos_facebook.api');
    $resp = $this->deleteGroup($groupId,$facebook);
    return $this->redirect($this->generateUrl('site_facebook_display_admin'));
    /* return $this->render('SiteFacebookDisplayBundle:Default:index.html.twig',array('idgroup' => $groupId));*/
  }
    
  //MessageAction
  public function messageAction(Request $request)
  {
    $facebook = $this->get('fos_facebook.api');
    $groups = $this->getGroupsApp($facebook);
    $teakts=$request->query->get('teakts');
    if($teakts = "messageCible")
      {
	$cible=$request->query->get('cible');
      }
    $message=$request->query->get('message');
    $link=$request->query->get('lien');
    if($teakts = "MessageGroupe")
      {
	foreach($groups['data'] as $group)
	  {
	    $send=$facebook->api($group['id']."/feed","POST",array('message' => $message ,'access_token'=>$facebook->getApplicationAccessToken()));
	  }
      }
    else
    $send=$facebook->api($cible."/feed","POST",array('message' => $message ,'access_token'=>$facebook->getApplicationAccessToken()));
   
     return $this->redirect($this->generateUrl('site_facebook_display_admin'));
  }

  public function adminAction (Request $request)
  {
    $facebook = $this->get('fos_facebook.api');
    $groups= $this->membersGroups($facebook);
    
    return $this->render('SiteFacebookDisplayBundle:Default:gestionFacebook.html.twig',array('groups' => $groups));
  }

  public function mosaiqueAction()
  {
    $facebook = $this->get('fos_facebook.api');
    $groups= $this->getGroupsApp($facebook);
    return $this->render('SiteFacebookDisplayBundle:Default:mosaique.html.twig',array('groups' => $groups));
  }

  public function joindregroupAction($uId,$groupId)
  {
    $facebook = $this->get('fos_facebook.api');
    
    $uid=$facebook->getUser();
    $helper= $facebook->getLoginUrl();
    $invit = $this->inviterGroup($groupId,$uid,$facebook);
    
    return $this->redirect($this->generateUrl('site_facebook_display_homepage',array('groupId'=>$groupId)));
  }
  
  public function deletememberAction($member,$grpId)
  {
    $facebook = $this->get('fos_facebook.api');
    $response = $this->deletememberAction($member,$grpId,$facebook);

    return $this->render('SiteFacebookDisplayBundle:Default:gestionFacebook.html.twig');
    
  }
   

  public function testAction(Request $request)
  {
    $facebook = $this->get('fos_facebook.api');
    $resp = $this->membersGroups($facebook);
    
      
    return $this->render('SiteFacebookDisplayBundle:Default:index.html.twig',array('response'=>$resp));
  }


  protected function ExCatch(FacebookApiException $e,BaseFacebook $facebook){
    $login_url= $facebook->getLoginUrl();
    $error_type= $e->getType();
    $error_log= $e->getMessage();
    return new Response('Please <a href="'.$login_url.'">login</a></br><p>'.$error_type.'</br>'.$error_log.'</p>');

  }
}